package com.triones.api.service.interlace.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.php.OpenCardStatus;
import com.ruoyi.common.enums.php.OpenCardTransactionType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.triones.api.entity.*;
import com.triones.api.entity.interlace.bo.InterlaceCardApplyParams;
import com.triones.api.entity.interlace.bo.InterlaceCardTransactionParams;
import com.triones.api.entity.interlace.bo.InterlaceInfinityCardParams;
import com.triones.api.entity.interlace.bo.request.BudgetChangeRequest;
import com.triones.api.entity.interlace.bo.request.DeleteCardRequest;
import com.triones.api.entity.interlace.bo.request.GetCardRequest;
import com.triones.api.entity.interlace.bo.request.ListAllBalancesRequest;
import com.triones.api.entity.interlace.dto.*;
import com.triones.api.entity.interlace.vo.*;
import com.triones.api.entity.vo.CountryDictVO;
import com.triones.api.entity.vo.FeeThaliVO;
import com.triones.api.mapper.CardMgrFeeMapper;
import com.triones.api.mapper.CountryDictMapper;
import com.triones.api.mapper.FeeThaliMapper;
import com.triones.api.mapper.StateDictMapper;
import com.triones.api.mapper.interlace.*;
import com.triones.api.service.interlace.InterlaceCardBillStatisticsService;
import com.triones.api.service.interlace.InterlaceCardService;
import com.triones.api.service.interlace.InterlaceCommunalService;
import com.triones.api.service.third.InterlaceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 卡管理
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InterlaceCardServiceImpl implements InterlaceCardService {

    private final InterlaceService interlaceService;

    private final InterlaceInfinityCardMapper interlaceInfinityCardMapper;

    private final CountryDictMapper countryDictMapper;

    private final StateDictMapper stateDictMapper;

    private final InterlaceShipPhysicalCardsMapper interlaceShipPhysicalCardsMapper;

    private final CardMgrFeeMapper cardMgrFeeMapper;

    private final FeeThaliMapper feeThaliMapper;

    private final InterlaceBalancesMapper interlaceBalancesMapper;

    private final InterlaceBudgetMapper interlaceBudgetMapper;

    private final InterlaceCommunalService interlaceCommunalService;

    private final InterlaceCardTransactionFeeMapper interlaceCardTransactionFeeMapper;

    private final InterlaceCardTransactionMapper interlaceCardTransactionMapper;

    private final InterlaceCardBillStatisticsMapper interlaceCardBillStatisticsMapper;

    private final InterlaceCardBillStatisticsService interlaceCardBillStatisticsService;

    private volatile boolean isExecuted = false;

    @Override
    public TableDataInfo<CustomInterlaceInfinityCardVO> pageList(InterlaceInfinityCardParams cardParams, PageQuery pageQuery) {
        Map<String, Object> params = cardParams.getParams();
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.like(StringUtils.isNotEmpty(cardParams.getCardNo()), "tiic.card_no", cardParams.getCardNo());
        wrapper.and(StringUtils.isNotEmpty(cardParams.getMember()), qr ->
            qr.like("tim.first_name", cardParams.getMember()).or()
                .like("tim.last_name", cardParams.getMember()).or()
                .like("tim.email", cardParams.getMember()).or()
                .like("tim.user_no", cardParams.getMember()).or()
                .like("tim.nickname", cardParams.getMember())
        );
        wrapper.eq(StringUtils.isNotEmpty(cardParams.getStatus()), "tiic.status", cardParams.getStatus());
        wrapper.eq(StringUtils.isNotEmpty(cardParams.getCardMode()), "tiic.cardMode", cardParams.getCardMode());
        wrapper.eq(StringUtils.isNotEmpty(cardParams.getNetwork()), "tiic.network", cardParams.getCardMode());
        wrapper.between(params.get("beginTime") != null && params.get("endTime") != null,
            "tiic.create_time", params.get("beginTime"), params.get("endTime"));
        wrapper.orderByDesc("tiic.create_time");
        Page<CustomInterlaceInfinityCardVO> page = interlaceInfinityCardMapper.selectPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(page);
    }

    @Override
    public CustomInterlaceInfinityCardVO getDetail(Long id) {
        InterlaceInfinityCardDO interlaceInfinityCardDO = interlaceInfinityCardMapper.selectById(id);
        try {
            if (interlaceInfinityCardDO != null) {
                /** 发起获取卡详情 */
                GetCardRequest request = new GetCardRequest();
                Map cardResponse = interlaceService.getCard(request, interlaceInfinityCardDO.getCardId());
                if (cardResponse != null) {
                    interlaceInfinityCardDO.setStatus(cardResponse.get("status").toString());
                    interlaceInfinityCardDO.setCardholderId(cardResponse.get("cardholderId").toString());
                    Map statistics = (Map) cardResponse.get("statistics");
                    interlaceInfinityCardDO.setStatisticsConsumption(Convert.toBigDecimal(statistics.get("consumption"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setStatisticsReversal(Convert.toBigDecimal(statistics.get("reversal"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setStatisticsReversalFee(Convert.toBigDecimal(statistics.get("reversalFee"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setStatisticsRefund(Convert.toBigDecimal(statistics.get("refund"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setStatisticsRefundFee(Convert.toBigDecimal(statistics.get("refundFee"), BigDecimal.ZERO));
                    interlaceInfinityCardDO.setStatisticsNetConsumption(Convert.toBigDecimal(statistics.get("netConsumption"), BigDecimal.ZERO));
                    Map velocityControl = (Map) cardResponse.get("velocityControl");
                    if (velocityControl != null) {
                        interlaceInfinityCardDO.setVelocityControlLimit(Convert.toStr(velocityControl.get("limit")));
                        interlaceInfinityCardDO.setVelocityControlType(Convert.toStr(velocityControl.get("type")));
                    }
                    Map balance = (Map) cardResponse.get("balance");
                    if (balance != null) {
                        interlaceInfinityCardDO.setBalanceCurrency(Convert.toStr(balance.get("currency")));
                        interlaceInfinityCardDO.setBalanceAvailable(Convert.toBigDecimal(balance.get("available")));
                        interlaceInfinityCardDO.setBalancePending(Convert.toBigDecimal(balance.get("pending")));
                        interlaceInfinityCardDO.setBalanceFrozen(Convert.toBigDecimal(balance.get("frozen")));
                    }
                    interlaceInfinityCardDO.setUpdateTime(System.currentTimeMillis());
                    interlaceInfinityCardMapper.updateById(interlaceInfinityCardDO);
                }
            }
        } catch (Exception e) {
            log.error("获取卡详情异常", e);
        }
        CustomInterlaceInfinityCardVO vo = new CustomInterlaceInfinityCardVO();
        BeanUtil.copyProperties(interlaceInfinityCardDO, vo);
        if (vo != null) {
            CountryDictDO billCountry = countryDictMapper.selectOne(new LambdaQueryWrapper<CountryDictDO>()
                .eq(CountryDictDO::getNationalityCountryCode, vo.getBillingAddressCountry()));
            if (billCountry != null) {
                StateDictDO billState = stateDictMapper.selectOne(new LambdaQueryWrapper<StateDictDO>()
                    .eq(StateDictDO::getCountryCode, vo.getBillingAddressCountry())
                    .eq(StateDictDO::getCode, vo.getBillingAddressState()));
                if (billState != null) {
                    vo.setBillingAddressState(billState.getEnName());
                }
                vo.setBillingAddressCountry(billCountry.getEnName());
            }
            if ("PhysicalCard".equals(vo.getCardMode())) {
                InterlaceShipPhysicalCardsVO physicalCardsVO = interlaceShipPhysicalCardsMapper.selectVoOne(new LambdaQueryWrapper<InterlaceShipPhysicalCardsDO>()
                    .eq(InterlaceShipPhysicalCardsDO::getCardId, vo.getCardId())
                    .last("limit 1"));
                if (physicalCardsVO != null) {
                    CountryDictDO shipCountry = countryDictMapper.selectOne(new LambdaQueryWrapper<CountryDictDO>()
                        .eq(CountryDictDO::getNationalityCountryCode, physicalCardsVO.getShipCountry()));
                    if (shipCountry != null) {
                        StateDictDO shipState = stateDictMapper.selectOne(new LambdaQueryWrapper<StateDictDO>()
                            .eq(StateDictDO::getCountryCode, physicalCardsVO.getShipCountry())
                            .eq(StateDictDO::getCode, physicalCardsVO.getShipState()));
                        if (shipState != null) {
                            physicalCardsVO.setShipState(shipState.getEnName());
                        }
                        physicalCardsVO.setShipCountry(shipCountry.getEnName());
                    }
                    vo.setShip(physicalCardsVO);
                }
            }
        }
        return vo;
    }

    @Override
    public TableDataInfo<CustomInterlaceCardTransactionVO> transactionPageList(InterlaceCardTransactionParams transactionParams, PageQuery pageQuery) {
        Map<String, Object> params = transactionParams.getParams();
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.like(StringUtils.isNotEmpty(transactionParams.getCardNo()), "tiic.card_no", transactionParams.getCardNo());
        wrapper.and(StringUtils.isNotEmpty(transactionParams.getMember()), qr ->
            qr.like("tim.first_name", transactionParams.getMember()).or()
                .like("tim.last_name", transactionParams.getMember()).or()
                .like("tim.email", transactionParams.getMember()).or()
                .like("tim.user_no", transactionParams.getMember()).or()
                .like("tim.nickname", transactionParams.getMember())
        );
        wrapper.eq(StringUtils.isNotEmpty(transactionParams.getStatus()), "tict.status", transactionParams.getStatus());
        wrapper.eq(StringUtils.isNotEmpty(transactionParams.getSn()), "tict.sn", transactionParams.getSn());
        wrapper.eq(StringUtils.isNotEmpty(transactionParams.getType()), "tict.type", transactionParams.getType());
        wrapper.between(params.get("beginTime") != null && params.get("endTime") != null,
            "tict.create_time", params.get("beginTime"), params.get("endTime"));
        wrapper.orderByDesc("tict.create_time");
        Page<CustomInterlaceCardTransactionVO> result = interlaceInfinityCardMapper.selectTransactionPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public CustomInterlaceCardTransactionVO getTransactionDetail(Long id) {
        CustomInterlaceCardTransactionVO transactionDetail = interlaceInfinityCardMapper.getTransactionDetail(id);
        if (transactionDetail != null) {
            transactionDetail.setFees(interlaceCardTransactionFeeMapper.selectVoList(new LambdaQueryWrapper<InterlaceCardTransactionFeeDO>()
                .eq(InterlaceCardTransactionFeeDO::getTid, id)));
        }
        return transactionDetail;
    }

    @Override
    public TableDataInfo<InterlaceCardApplyVO> applyPageList(InterlaceCardApplyParams applyParams, PageQuery pageQuery) {
        Map<String, Object> params = applyParams.getParams();
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.like(StringUtils.isNotEmpty(applyParams.getNetwork()), "tica.network", applyParams.getNetwork());
        wrapper.like(StringUtils.isNotEmpty(applyParams.getCurrencies()), "tica.currencies", applyParams.getCurrencies());
        wrapper.and(StringUtils.isNotEmpty(applyParams.getMember()), qr ->
            qr.like("tim.first_name", applyParams.getMember()).or()
                .like("tim.last_name", applyParams.getMember()).or()
                .like("tim.email", applyParams.getMember()).or()
                .like("tim.user_no", applyParams.getMember()).or()
                .like("tim.nickname", applyParams.getMember())
        );
        wrapper.eq(StringUtils.isNotEmpty(applyParams.getStatus()), "tica.status", applyParams.getStatus());
        wrapper.eq(StringUtils.isNotEmpty(applyParams.getCardMode()), "tica.cardMode", applyParams.getCardMode());
        wrapper.between(params.get("beginTime") != null && params.get("endTime") != null,
            "tica.create_time", params.get("beginTime"), params.get("endTime"));
        wrapper.orderByDesc("tica.create_time");
        Page<InterlaceCardApplyVO> result = interlaceInfinityCardMapper.selectApplyPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public boolean delCard(Long id) {
        InterlaceInfinityCardDO infinityCardDO = interlaceInfinityCardMapper.selectById(id);
        if (infinityCardDO == null) {
            throw new ServiceException("卡不存在！");
        }
        DeleteCardRequest request = new DeleteCardRequest();
        request.setCardId(infinityCardDO.getCardId());
        if (interlaceService.deleteCard(request)) {
            infinityCardDO.setStatus("Inactive");
            interlaceInfinityCardMapper.updateById(infinityCardDO);
        }
        return true;
    }

    /**
     * 定时收取卡片管理费用（每个小时执行一次）
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void collectCardMgrFee() {
        /** 查询待收取的记录 */
        LambdaQueryWrapper<CardMgrFeeDO> lqw = new LambdaQueryWrapper<CardMgrFeeDO>();
        lqw.eq(CardMgrFeeDO::getStatus, "0");
        List<CardMgrFeeDO> mgrFeeList = cardMgrFeeMapper.selectList(lqw);
        if (mgrFeeList != null && mgrFeeList.size() > 0) {
            for (CardMgrFeeDO item : mgrFeeList) {
                /** 查询用户的预算账户 */
                InterlaceBalancesDO balances = interlaceBalancesMapper.selectOne(new LambdaQueryWrapper<InterlaceBalancesDO>()
                    .eq(InterlaceBalancesDO::getUid, item.getUid())
                    .eq(InterlaceBalancesDO::getWalletType, "Budget")
                    .eq(InterlaceBalancesDO::getCurrency, "USD")
                    .last("limit 1 FOR UPDATE"));
                if (balances != null) {
                    BigDecimal balance = balances.getAvailable();
                    /** 判断账户余额是否足够 */
                    if (balance.compareTo(item.getCollectAmount()) > 0) {
                        InterlaceBudgetDO budget = interlaceBudgetMapper.selectOne(new LambdaQueryWrapper<InterlaceBudgetDO>()
                            .eq(InterlaceBudgetDO::getUid, item.getUid())
                            .eq(InterlaceBudgetDO::getBalanceId, balances.getBid()));
                        if (budget != null) {
                            /** 发起预算减少 */
                            String clientTransactionId = IdempotentKeyGenerator.generateIdempotentKey();
                            BudgetChangeRequest budgetChangeRequest = new BudgetChangeRequest();
                            budgetChangeRequest.setBudgetId(budget.getRid());
                            budgetChangeRequest.setCost(item.getCollectAmount());
                            budgetChangeRequest.setClientTransactionId(clientTransactionId);
                            Boolean budgetBalanceResponse = interlaceService.decreaseTheBudgetBalance(budgetChangeRequest);
                            if (budgetBalanceResponse) {
                                /** 记录量子账户 */
                                InterlaceQuantumTransferDO quantumTransferDO = new InterlaceQuantumTransferDO();
                                quantumTransferDO.setUid(item.getUid());
                                quantumTransferDO.setAccountId(budget.getAccountId());
                                quantumTransferDO.setType("card_mgt");
                                quantumTransferDO.setAmount(item.getCollectAmount());
                                quantumTransferDO.setTransferObj(item.getCardId());
                                quantumTransferDO.setTransferId(clientTransactionId);
                                quantumTransferDO.setAdditional1(item.getCardNo());
                                quantumTransferDO.setStatus("Pending");
                                quantumTransferDO.setCreateTime(System.currentTimeMillis());
                                quantumTransferDO.setUpdateTime(System.currentTimeMillis());
                                interlaceCommunalService.addQuantumTransfer(quantumTransferDO);

                                /** 更新balance */
                                ListAllBalancesRequest balancesRequest = new ListAllBalancesRequest();
                                balancesRequest.setAccountId(budget.getAccountId());
                                balancesRequest.setLimit("10");
                                balancesRequest.setPage("0");
                                balancesRequest.setWalletType("Budget");
                                interlaceCommunalService.updateBalances(balancesRequest);

                                /** 更新收取记录 */
                                item.setStatus("2");
                                item.setTransferId(clientTransactionId);
                                item.setUpdateAt(System.currentTimeMillis());
                                cardMgrFeeMapper.updateById(item);

                                /** 添加银行卡的费用记录 */
                                String sn = SnCreator.generateQTSn();
                                InterlaceCardTransactionDO cardTransactionDO = new InterlaceCardTransactionDO();
                                cardTransactionDO.setUid(item.getUid());
                                cardTransactionDO.setSn(sn);
                                cardTransactionDO.setAccountId(budget.getAccountId());
                                cardTransactionDO.setRid(clientTransactionId);
                                cardTransactionDO.setCardId(item.getCardId());
                                cardTransactionDO.setCurrency("USD");
                                cardTransactionDO.setAmount(item.getCollectAmount());
                                cardTransactionDO.setType("Card_Mgt_Fee");
                                cardTransactionDO.setClientTransactionId(clientTransactionId);
                                cardTransactionDO.setCardTransactionId(clientTransactionId);
                                cardTransactionDO.setStatus("Closed");
                                cardTransactionDO.setTransactionTime(System.currentTimeMillis());
                                cardTransactionDO.setTransactionCurrency("USD");
                                cardTransactionDO.setTransactionAmount(item.getCollectAmount());
                                cardTransactionDO.setMerchantName("Card Management Fee");
                                cardTransactionDO.setCreateTime(System.currentTimeMillis());
                                cardTransactionDO.setUpdateTime(System.currentTimeMillis());
                                cardTransactionDO.setFee(BigDecimal.ZERO);
                                interlaceCardTransactionMapper.insert(cardTransactionDO);

                                /** 统计账单 */
                                interlaceCardBillStatisticsService.decreaseAmount(item.getCardId(), item.getCollectAmount());
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 定时创建卡片管理费用（每天10点）
     */
    @Scheduled(cron = "0 0 10 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void createCardMgrFee() {
        BigDecimal cardMgtFee = Convert.toBigDecimal(5.00);
        FeeThaliVO feeThaliVO = feeThaliMapper.selectVoOne(new LambdaQueryWrapper<FeeThaliDO>()
            .eq(FeeThaliDO::getType, "card_mgt")
            .eq(FeeThaliDO::getStatus, "0")
            .last("limit 1"));
        if (feeThaliVO != null) {
            cardMgtFee = Convert.toBigDecimal(feeThaliVO.getFeeConfig());
        }
        String createMonth = DateUtil.timestampToDateStr();
        LambdaQueryWrapper<InterlaceInfinityCardDO> lqw = new LambdaQueryWrapper<InterlaceInfinityCardDO>();
        lqw.in(InterlaceInfinityCardDO::getStatus, "Active", "Frozen", "Control", "Pending");
        List<InterlaceInfinityCardDO> cardList = interlaceInfinityCardMapper.selectList(lqw);
        if (cardList.size() > 0) {
            List<CardMgrFeeDO> list = new ArrayList<>();
            for (InterlaceInfinityCardDO item : cardList) {
                /** 最近一条创建记录 */
                CardMgrFeeDO mgrFeeDO = cardMgrFeeMapper.selectOne(new LambdaQueryWrapper<CardMgrFeeDO>()
                    .eq(CardMgrFeeDO::getCardId, item.getCardId())
                    .orderByDesc(CardMgrFeeDO::getCreateAt)
                    .last("limit 1"));
                if (mgrFeeDO != null) {
                    if (CardMgtFeeUtil.shouldChargeManagementFee(DateUtil.timestampToDateStrToyyyyMMdd(), mgrFeeDO.getDeadlineTime())) {
                        CardMgrFeeDO oldDO = cardMgrFeeMapper.selectOne(new LambdaQueryWrapper<CardMgrFeeDO>()
                            .eq(CardMgrFeeDO::getCardId, item.getCardId())
                            .eq(CardMgrFeeDO::getCollectMonth,createMonth)
                            .last("limit 1"));
                        if (oldDO == null) {
                            CardMgrFeeDO nextTime = new CardMgrFeeDO();
                            nextTime.setUid(item.getUid());
                            nextTime.setCardId(item.getCardId());
                            nextTime.setCardNo(item.getCardNo());
                            nextTime.setCollectMonth(createMonth);
                            nextTime.setCreateAt(System.currentTimeMillis());
                            nextTime.setUpdateAt(System.currentTimeMillis());
                            nextTime.setCollectAmount(cardMgtFee);
                            nextTime.setStartTime(DateUtil.timestampToDateStrToyyyyMMdd());
                            nextTime.setDeadlineTime(CardMgtFeeUtil.calculateNextChargeDate(DateUtil.timestampToDateStrToyyyyMMdd()));
                            nextTime.setStatus("0");
                            list.add(nextTime);
                        }
                    }
                } else {
                    mgrFeeDO = new CardMgrFeeDO();
                    mgrFeeDO.setUid(item.getUid());
                    mgrFeeDO.setCardId(item.getCardId());
                    mgrFeeDO.setCardNo(item.getCardNo());
                    mgrFeeDO.setCollectMonth(createMonth);
                    mgrFeeDO.setCreateAt(System.currentTimeMillis());
                    mgrFeeDO.setUpdateAt(System.currentTimeMillis());
                    mgrFeeDO.setCollectAmount(cardMgtFee);
                    mgrFeeDO.setStartTime(DateUtil.timestampToDateStrToyyyyMMdd());
                    mgrFeeDO.setDeadlineTime(CardMgtFeeUtil.calculateNextChargeDate(DateUtil.timestampToDateStrToyyyyMMdd()));
                    mgrFeeDO.setStatus("0");
                    list.add(mgrFeeDO);
                }
            }
            if (list.size() > 0) {
                cardMgrFeeMapper.insertBatch(list);
            }
        }
    }

    /**
     * 每个月1号创建卡账单
     */
    @Scheduled(cron = "0 0 0 1 * ?")
    public void createCardBillList() {
        LambdaQueryWrapper<InterlaceInfinityCardDO> lqw = new LambdaQueryWrapper<InterlaceInfinityCardDO>();
        lqw.in(InterlaceInfinityCardDO::getStatus, "Active", "Frozen", "Control", "Pending");
        List<InterlaceInfinityCardDO> cardList = interlaceInfinityCardMapper.selectList(lqw);
        if (cardList.size() > 0) {
            List<InterlaceCardBillStatisticsDO> list = new ArrayList<>();
            for (InterlaceInfinityCardDO item : cardList) {
                InterlaceCardBillStatisticsDO cardBillStatisticsDO = interlaceCardBillStatisticsMapper.selectOne(new LambdaQueryWrapper<InterlaceCardBillStatisticsDO>()
                    .eq(InterlaceCardBillStatisticsDO::getCid, item.getId())
                    .eq(InterlaceCardBillStatisticsDO::getBillYear, DateUtils.getNowYearStr())
                    .eq(InterlaceCardBillStatisticsDO::getBillMonth, DateUtils.getNowMonthWithZero()));
                if (cardBillStatisticsDO == null) {
                    InterlaceCardBillStatisticsDO billStatisticsDO = new InterlaceCardBillStatisticsDO();
                    billStatisticsDO.setCid(item.getId());
                    billStatisticsDO.setCardId(item.getCardId());
                    billStatisticsDO.setUid(item.getUid());
                    billStatisticsDO.setBillYear(DateUtils.getNowYearStr());
                    billStatisticsDO.setBillMonth(DateUtils.getNowMonthWithZero());
                    billStatisticsDO.setStartDay("01");
                    billStatisticsDO.setEndDay(DateUtils.getMaxDayOfMonthStr());
                    billStatisticsDO.setAmount(BigDecimal.ZERO);
                    billStatisticsDO.setLastDate(System.currentTimeMillis());
                    list.add(billStatisticsDO);
                }
            }
            if (list.size() > 0) {
                interlaceCardBillStatisticsMapper.insertBatch(list);
            }
        }
    }

    /**
     * 第一次执行后，延迟极长时间（等效只执行一次）
     */
//    @Scheduled(fixedDelay = Long.MAX_VALUE)
    public void executeOnce() {
        if (!isExecuted) {
            // 执行任务逻辑

            // 标记为已执行
            isExecuted = true;
        }
    }
}
